//
//  YYMemberDetailVC.m
//  drivingSchool
//
//  Created by 子yu 刘 on 2018/9/25.
//  Copyright © 2018年 子yu 刘. All rights reserved.
//

#import "YYMemberDetailVC.h"
#import "YYMemberDetailCell.h"
#import "YYPayVC.h"

@interface YYMemberDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong)NSArray * dataArr;
@property (nonatomic ,strong)NSDictionary * dataDic;
@end

@implementation YYMemberDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
}

- (void)getData{
    [RequestOperationManager giftDetail_pid:self.pid success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            self.dataDic = [result[@"data"][@"list"] copy];
             self.dataArr = [result[@"data"][@"lists"] copy];
            [self reloadData];
        }
        
    } failture:^(NSError *error) {
        
    }];
}

- (void)reloadData{
    [self.bigImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DEF_INTERFACE_WEBVIEWSERVICE,self.dataDic[@"image"]]]];
    self.lbPrivilege.text  = _dataDic[@"privilege"];
    self.lbAddress.text = _dataDic[@"address"];
    self.lbPrice.text = [NSString stringWithFormat:@"礼包价格：￥%@元",_dataDic[@"price"]];
    [self.tableView reloadData];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YYMemberDetailCell * cell = [tableView dequeueReusableCellWithIdentifier:@"YYMemberDetailCell"];
    NSDictionary * itme = _dataArr[indexPath.row];
    cell.lbName.text = itme[@"goods"];
    cell.lbContent.text = itme[@"content"];
    
    return cell;
}

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell
                                                            *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableHeight.constant =  tableView.contentSize.height;
            
        });
        
    
}

- (IBAction)buy:(id)sender {
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:@"iOS" forKey:@"source"];
    YYPayVC * pay = (YYPayVC *)[CFUtility getVC:@"YYPayVC" Storyboard:HOME];
    pay.isHidden = YES;
    pay.money = _dataDic[@"price"];
    MJWeakSelf;
    pay.payBlock = ^(NSString *type) {
        if ([type isEqualToString:@"0"]) {
            [RequestOperationManager giftbuyAlipays_price:weakSelf.dataDic[@"price"] gift_id: weakSelf.dataDic[@"id"] success:^(id result) {
                if (DEF_REQ_SUCCESS) {
                    [self aliPayWithSign:result[@"data"]];
                }
            } failture:^(NSError *error) {
                
            }];
          
        }else{
            [RequestOperationManager giftWechatpay_price:weakSelf.dataDic[@"price"]  gift_id:weakSelf.dataDic[@"id"]  success:^(id result) {
                if (DEF_REQ_SUCCESS) {
                    [self wechatPayWithResponse:result[@"data"]] ;
                }
            } failture:^(NSError *error) {
                
            }];
        
        }
        
    };
    [self.navigationController pushViewController:pay animated:YES];
}


- (void)wechatPayWithResponse:(NSDictionary *)response {
    PayReq* req  = [[PayReq alloc] init];
    req.partnerId = response[@"partnerid"];
    req.prepayId= response[@"prepayid"];
    req.package = response[@"package"];
    req.nonceStr= response[@"noncestr"];
    req.timeStamp= [response[@"timestamp"] intValue];
    req.sign=response[@"sign"];
    [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        
        if (errCode == FLErrCodeSuccess) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (void)aliPayWithSign:(NSString * )sign{
    /**
     *  @author gitKong
     *
     *  来自支付宝文档数据
     */
    
    [FLPAYMANAGER fl_payWithOrderMessage:sign callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (resultDic&&[resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
            
        }
        
    }];
    
    
}


- (NSString *)jumpToBizPay {
    //============================================================
    /**
     *  @author Clarence
     *
     *  来自微信文档数据
     */
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
                    NSLog(@"errCode = %zd,errStr = %@",errCode,errStr);
                }];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
    
}



@end
